package com.sunxueqi.framework.web.controller;

import java.beans.PropertyEditorSupport;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.sunxueqi.common.util.ServletUtils;
import com.sunxueqi.common.util.SqlUtil;
import com.sunxueqi.framework.web.vo.ResponseData;
import com.sunxueqi.framework.web.vo.ResponseTableData;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @description: web层通用数据处理
 * @author 10906
 *
 */
@Slf4j
public class BaseController {
	
	/**
	 * 分页开始的索引
	 */
	public static final String PAGE_NUM = "pageNum";
	/**
	 * 每页显示的数量
	 */
	public static final String PAGE_SIZE = "pageSize";
	/**
	 * 排序列
	 */
	public static final String ORDER_BY_COLUMN = "orderByColumn";
	/**
	 * 排序方向 "desc" 或者 "asc"
	 */
	public static final String IS_ASC = "isAsc";

	/**
	 * 将前台日期格式的字符串，自动转换为Date类型
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		log.debug("BaseController initBinder");
		
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			public void setAsTest(String dateStr) {
				setValue(DateUtil.parse(dateStr));
			}
		});
	}
	
	
	/**
	 * 封装的分页查询方法
	 */
	protected void startPage() {
		
		Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM);
		Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE);
		
		if(ObjectUtil.isNotEmpty(pageNum) && ObjectUtil.isNotEmpty(pageSize)) {
			PageMethod.startPage(pageNum, pageSize, getOrderBy());
		}
	}
	
	/**
	 * 获取排序方式
	 * @return
	 */
	public String getOrderBy() {
		String orderByColumn = ServletUtils.getParameter(ORDER_BY_COLUMN);
		SqlUtil.escapeOrderBySql(orderByColumn);
		orderByColumn = StrUtil.isEmpty(orderByColumn) ? "create_time" : orderByColumn;
		String isAsc = ServletUtils.getParameter(IS_ASC);
		
		String result = orderByColumn + " "+ isAsc;
		return result;
	}
	
	/**
	 * 响应的分页数据
	 * @param list
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected ResponseTableData getResponseTableData(List<?> list) {
		log.debug("BaseController getResponseData");
		
		ResponseTableData respData = new ResponseTableData();
		respData.setCode(HttpStatus.OK.value());
		respData.setRows(list);
		if(list == null) {
			list = new ArrayList<>();
		}
		respData.setTotal(new PageInfo(list).getTotal());
		return respData;
	}
	
	/**
	 * 返回响应结果
	 * @param rows 影响的行数
	 * @return 响应结果
	 */
	protected ResponseData getResponseData(int rows) {
		return rows > 0 ? ResponseData.success() : ResponseData.error();
	}
	

	
}
